import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import cloud from 'wx-server-sdk'

import { ReturnReportResponse, SCFFaaSEvent, SCFHttpEvent } from './type'

cloud.init({
  env: 'dev-vmpu6',
  throwOnNotFound: false,
} as any)

const db = cloud.database()

export async function main(event: SCFHttpEvent & SCFFaaSEvent) {
  console.log('请求参数：', event)


  /**
   * 问卷调查 Webhook ,后端主动推送
   */
  if (event?.httpMethod) {
    const router = new HttpRouter()
    return await router.handleRequest(event)
  }

  /**
   * 小程序调用云函数
   */
  const router = new FaaSRouter()

  return await router.handleInvoke(event)
}

class FaaSRouter {

  async handleInvoke(event: SCFFaaSEvent) {
    debugger
    switch (event.method) {
      case 'anonymous_report'://无接触打卡
        return this.handleAnonymousReport(event.data)
      case 'stat':
        return this.handleStat()
      case 'stat_by_orgName'://返岗登记
        return this.handleQueryStateByOrgName(event.data)
      case 'return_report'://返岗登记
        return this.handleUpdateReturnReport(event.data)
      case 'get_org_info'://获取机构信息
        return this.handleGetOrgInfo(event.data)
    }
  }

  //查询14天内同机构数据
  async handleQueryStateByOrgName(params) {
    const dbcommand = db.command
    const context = cloud.getWXContext()
    const collection = db.collection('return_report')
    const now = moment().valueOf() ;//当天
    const last14 = moment().subtract(14,'days').valueOf();//14天前
    const totalCount = await collection.where({ updateTime: dbcommand.gte(last14).and(dbcommand.lte(now)), orgSecrt: params.org_secrt }).count()//
    const hotCount = await collection.where({ updateTime: dbcommand.gte(last14).and(dbcommand.lte(now)), orgSecrt: params.org_secrt, feswitch: true }).count()//
    const closeCount = await collection.where({ updateTime: dbcommand.gte(last14).and(dbcommand.lte(now)), orgSecrt: params.org_secrt, jcswitch: true }).count()//

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {
        totalCount: totalCount,
        hotCount: hotCount,
        closeCount: closeCount
      }
    }
  }

  //提交返工上报
  async handleUpdateReturnReport(data) {
    const context = cloud.getWXContext()
    const collection = db.collection('return_report')
    console.log("监听handleUpdateReturnReport")
    data.openId = context.OPENID
    data.updateTime = moment().valueOf()
   
    const result = await collection
      .where({ openId: data.openId, updateDate: data.updateDate })
      .get()

    if (result.data.length === 0) {
      await collection.add({ data })
    } else {
      await collection
        .where({ openId: data.openId, updateDate: data.updateDate })
        .update({ data })
    }

    return {
      message: '更新成功',
      status: 0,
      error: null,
      data: {
        openId: context.OPENID
      }
    }
  }
  //获取机构信息
  async handleGetOrgInfo(params) {
    const context = cloud.getWXContext()
    const collection = db.collection('organization')
    console.log("监听handleGetOrgInfo")

    const data = await collection.where({ org_secrt: params.org_secrt }).get()

    return {
      message: '请求成功',
      status: 0,
      error: null,
      data: data.data
    }
  }

  async handleStat() {
    const context = cloud.getWXContext()
    const collection = db.collection('healthy_report')

    const count = await collection.where({ date: moment().format('YYYY-MM-DD hh:mm:ss') }).count()

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {
        count: (count as any)?.total,
        openId: context.OPENID
      }
    }
  }

  /**
   * 无接触打卡
   */
  async handleAnonymousReport(params) {
    const context = cloud.getWXContext()
    const collection = db.collection('anonymous_report')

    const data = {
      date: moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss'),
      timespan: moment().valueOf(),
      openId: context.OPENID,
      content: params,
    }

    const result = await collection.add({ data })
    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {
        sign_date: moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss')
      }
    }
  }
}

class HttpRouter {

  handleRequest(event: SCFHttpEvent) {
    if (event?.httpMethod !== 'POST') {
      return {
        message: 'ok',
        status: 0,
        error: null,
        data: { event }
      }
    }

    const data = JSON.parse(event.body)

    switch (event.path) {
      case '/return_report':
        return this.handleReturnReport(data)
      case '/healthy_report':
        return this.handleHealthyReport(data)
    }
  }

  /**
   * 返校上报
   */
  handleReturnReport = async (body: ReturnReportResponse) => {
    console.log("监听handleReturnReport")
    /**
     * 字段及注释在 Typings 中
     */
    const { entry: {
      field_2,
      field_4,
      field_5,
      field_7,
      field_8,
      field_11,
      field_12,
      field_13,
      field_14,
    } }: ReturnReportResponse = body

    const data = {
      name: field_2,
      phone: field_4,
      return_date: field_5,
      transportation: field_7,
      transportation_info: field_8,
      city_footprint: field_11,
      wuhan: field_12 === '是',
      touch_wuhan: field_13 === '是',
      status: field_14,
      date: moment().subtract(8, 'hours').format('yyyy-MM-DD hh:mm:ss'),
    }

    const collection = db.collection('return_report')

    const result = await collection
      .where({ name: field_2, phone: field_4, })
      .get()

    if (result.data.length === 0) {
      await collection.add({ data })
    } else {
      await collection
        .where({ name: field_2, phone: field_4, })
        .update({ data })
    }

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {}
    }
  }


  handleHealthyReport = async (body) => {
    // 校园信息
    if (!body?.entry?.field_1) {
      return
    }

    const data = {
      date: moment().add(8, 'hours').format('yyyy-MM-DD hh:mm:ss'),
      ...body,
    }

    const collection = db.collection('healthy_report')
    await collection.add({ data })

    return {
      message: 'ok',
      status: 0,
      error: null,
      data: {}
    }
  }
}
